/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package myheartsgame;
import java.io.*;
import java.net.*;
import java.util.ArrayList;

/**
 *
 * @author KaKa
 */
public class Server implements Runnable{
    
    ServerSocket _sSocket;
    int _iPort = 3200;
    Thread _serverListener;
    public static boolean _isBroadcast = false;
    public static String _sName = "Server: ";
    // Server se quan ly 2 ket noi cua 1 client
    public static ArrayList<ConnectedSocketInfomation> _clientSocketManager;
    public static int _iNumberPlayer = 1;

    //Nguoi chia bai
    public static Dealer _dealer;

    Server() throws IOException{
        try {
            _clientSocketManager = new ArrayList<ConnectedSocketInfomation>();

            //Tao socket lang nghe ket noi
            _sSocket = new ServerSocket(_iPort);
            _serverListener = new Thread(this, _sName);
            _serverListener.start();
        }
        catch (IOException io) {            
            throw io;
        }
    }

    // Xoa thong tin 1 client
    // Chi can thong tin 1 socket listening
    public static void RemoveClient(Socket listening) {
        int iClient = _clientSocketManager.size();
        for(int iCount = 0; iCount < iClient; iCount++) {
            if(_clientSocketManager.get(iCount)._listening == listening) {
                _clientSocketManager.remove(iCount);
                return;
            }
        }
    }
    // Server se broadcast toi cac client khac
    // Tru client nao co exceptListeningSocket cua Server
    public static void BroadcastMessage(String message, Socket exceptListeningSocket) {
        _isBroadcast = true;

        int iCountSocket = _clientSocketManager.size();
        for (int i = 0; i < iCountSocket; i++) {
            if (_clientSocketManager.get(i)._listening != exceptListeningSocket) {
                SendMessage(message, _clientSocketManager.get(i)._talking);

            }
        }

        _isBroadcast = false;
    }

    // Gui cho 1 client voi socket la toClient
    public static void SendMessage(String message, Socket toClient){
        try {
            OutputStream os = toClient.getOutputStream();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));

            bw.write(message);
            bw.newLine();
            bw.flush();

        } catch (IOException io) {
        }
    }

    // Gui cho tat ca client
    public static void SendMessage(String message){
        try {
            // Gui cho tat ca client
            int iCountClient = _clientSocketManager.size();
            for (int i = 0; i < iCountClient; i++) {
                SendMessage(message, _clientSocketManager.get(i)._talking);

            }
        } catch (Exception ex) {
            System.out.println("Server cannot send message");
        }
    }

    public void run(){
        try {

            System.out.println("Waiting for a Client");

            do {
                // Neu du so nguoi thi bat dau chia bai
                if(_iNumberPlayer == 4)
                {
                    // Khoi tao bai va xao bai
                    _dealer = new Dealer();                    
                    ArrayList<String> serverCardsInfo = _dealer.DealToPlayer();
                    MainGame.InitPlayerCards(serverCardsInfo);
                    
                    ArrayList<String> player2CardsInfo = _dealer.DealToPlayer();
                    ArrayList<String> player3CardsInfo = _dealer.DealToPlayer();
                    ArrayList<String> player4CardsInfo = _dealer.DealToPlayer();

                    //Gui thong tin cac la bai cho nguoi choi
                    for(int iCount = 0; iCount < 13; iCount++) {
                        SendMessage("@CARDS@_" + player2CardsInfo.get(iCount), _clientSocketManager.get(0)._talking);
                        SendMessage("@CARDS@_" + player3CardsInfo.get(iCount), _clientSocketManager.get(1)._talking);
                        SendMessage("@CARDS@_" + player4CardsInfo.get(iCount), _clientSocketManager.get(2)._talking);
                    }
                    
                    // Chia bai
                    GlobalClass.isDealing = true;                    
                }

                // Moi lan client ket noi se co 2 socket
                // 1 socket lang nghe server se gui thong tin
                // 1 socket noi chuyen de server lang nghe
                Socket talkSocket = _sSocket.accept();                                
                Socket listenSocket = _sSocket.accept();

                if (_iNumberPlayer >= 4) {
                    //Gui thong bao den cho client roi tat ket noi
                    SendMessage("@Full@", talkSocket);
                    talkSocket.close();
                    listenSocket.close();
                    continue;
                } else {
                    SendMessage("@Success@", talkSocket);
                }

                // Them thong tin cua cac socket vao
                _clientSocketManager.add(new ConnectedSocketInfomation(listenSocket, talkSocket));                               
              
                // Tao mot ket noi rieng de noi chuyen voi player
                new ServerTalking(listenSocket, "player");
                _iNumberPlayer++;
                System.out.println("Have player " + _iNumberPlayer);

            } while (true);
        } catch (Exception ex) {
            System.out.println("Server run error.");
        }
    }
}

// Moi client ket noi toi se duoc tao 2 socket de lang nghe
// va de server noi chuyen.
class ConnectedSocketInfomation {

    String _clientName = "player";
    Socket _listening = null;
    Socket _talking = null;
    public ConnectedSocketInfomation(Socket listening, Socket talking) {
        _listening = listening;
        _talking = talking;
    }

    public void SetName(String name) {
        _clientName = name;
    }

}